package io.kiki.sba.registry.common.model;


import io.kiki.sba.registry.compress.CompressUtils;
import lombok.Getter;
import lombok.Setter;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Setter
@Getter
public class DataCenterPushInfo {

    private long pushVersion;

    private Map<String, SegmentPushInfo> segmentPushInfos = new HashMap<>();

    public DataCenterPushInfo() {
    }

    public DataCenterPushInfo(String dataCenter, long pushVersion, SegmentPushInfo segmentPushInfo) {
        this.pushVersion = pushVersion;
        segmentPushInfos.put(dataCenter, segmentPushInfo);
    }

    public DataCenterPushInfo(long pushVersion, Map<String, SegmentPushInfo> segmentPushInfos) {
        this.pushVersion = pushVersion;
        this.segmentPushInfos = segmentPushInfos;
    }


    public Set<String> getSegments() {
        if (segmentPushInfos == null) {
            return Collections.EMPTY_SET;
        }
        return segmentPushInfos.keySet();
    }

    public Map<String, Integer> getPushNum() {
        if (segmentPushInfos == null) {
            return Collections.EMPTY_MAP;
        }
        Map<String, Integer> ret = new HashMap<>();
        for (SegmentPushInfo value : segmentPushInfos.values()) {
            ret.put(value.getSegment(), value.getDataCount());
        }
        return ret;
    }

    public Map<String, String> getEncode() {
        if (segmentPushInfos == null) {
            return Collections.EMPTY_MAP;
        }
        Map<String, String> ret = new HashMap<>();
        for (SegmentPushInfo value : segmentPushInfos.values()) {
            ret.put(value.getSegment(), CompressUtils.normalizeEncode(value.getEncode()));
        }
        return ret;
    }

    public Map<String, Integer> getEncodeSize() {
        if (segmentPushInfos == null) {
            return Collections.EMPTY_MAP;
        }
        Map<String, Integer> ret = new HashMap<>();
        for (SegmentPushInfo value : segmentPushInfos.values()) {
            ret.put(value.getSegment(), value.getEncodeSize());
        }
        return ret;
    }

    public void addSegmentInfo(String segment, String encoding, int encodeSize) {
        SegmentPushInfo segmentPushInfo = segmentPushInfos.computeIfAbsent(segment, k -> new SegmentPushInfo(segment));
        segmentPushInfo.setEncode(encoding);
        segmentPushInfo.setEncodeSize(encodeSize);
    }
}
